export default {
  namespaced: true,
  state: function () {
    return {
      cartList: JSON.parse(uni.getStorageSync('cart') || '[]' ) 
    }
  },
  mutations: {
    allSelectedChangeState(state, checked){
      state.cartList.forEach(item => item.goods_state = !checked)
      this.commit('cart/storageCart')
      // state.cartList = state.cartList.forEach(item => item.goods_state = checked)
    },
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    addToCart(state, obj) {
     const cartItem = state.cartList.find(item => item.goods_id === obj.goods_id)
     console.log(cartItem)
     if(cartItem) {
       cartItem.goods_count += 1
     } else{
       state.cartList.push(obj)
     }
     console.log(state.cartList)
     this.commit('cart/storageCart')
    },
    storageCart(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cartList))
    },
    changeState(state, goods) {
      const item = state.cartList.find(ele => ele.goods_id === goods.goods_id)
      if(item) {
        item.goods_state = goods.goods_state
      }
      this.commit('cart/storageCart')
    },
    chageNum(state, goods) {
      const item = state.cartList.find(ele => ele.goods_id === goods.goods_id )
      if(item) {
        item.goods_count = goods.goods_count
        this.commit('cart/storageCart')
      }
    },
    delGoodsItem(state, goods) {
      state.cartList = state.cartList.filter(item => item.goods_id !== goods.goods_id)
      this.commit('cart/storageCart')
    }
  },
  getters: {
    total(state) {
      return state.cartList.reduce((start, item) => start + item.goods_count, 0)
    },
    selectCount(state) {
      return state.cartList.filter(ele => ele.goods_state).reduce((count, item) => count + item.goods_count, 0)
    },
    selectPrice(state) {
            return state.cartList.filter(ele => ele.goods_state).reduce((count, item) => count + item.goods_count * item.goods_price, 0).toFixed(2)
    }
  }
}